import {getMd5, validateEmail} from "../utils/index.js";
import {checkInviterCode, getNewToken, login, register} from "../api/user/api.js";
import router from "../route/index.js";
import {clearStorage} from "../utils/storage.js";

/**
 * 用户登录
 * @param account
 * @param passwordStr
 * @returns {Promise<void>}
 */
export const useLogin = async (account, passwordStr) => {
  let password = getMd5(passwordStr);
  // 判断登录账户的是名称还是邮箱
  let isEmail = validateEmail(account);
  let username;
  let email;
  isEmail ? email = account : username = account;
  // 这里应该向后端发起请求
  let result = await login(username, email, password);
  // 保存用户信息和token
  useSaveUserInfo(result);
  // 路由跳转
  await router.push("/Home");
};

/**
 * 用户注册
 * @param email
 * @param username
 * @param passwordStr
 * @param code
 * @returns {Promise<void>}
 */
export const useRegister = async (email, username, passwordStr, code) => {
  let result = await register(username, getMd5(passwordStr), email, code);
  console.log('useRegister', result);
  localStorage["token"] = result.token;
  localStorage["refreshToken"] = result.refreshToken;
  localStorage["id"] = result.id;
  // 进入系统
  useCheckToken();
};

/**
 * 用户退出
 */
export const useExit = () => {
  clearStorage();
  router.push('/')
};

/**
 * 用户检查验证码
 * @param code
 * @returns {Promise<boolean>}
 */
export const useCheckCode = async (code) => {
  let result = await checkInviterCode(code);
  return !!(result && result.result);

}

/**
 * 检查token是否过期，如果过期但是没过长时间直接获取新的token
 * @returns {Promise<void>}
 */
export const useCheckToken = async () => {
  let token = localStorage["token"];
  let refreshToken = localStorage["refreshToken"];
  if(!token && !refreshToken) {
    return;
  }
  let user = JSON.parse(decodeURIComponent(escape(window.atob(token.split('.')[1]))))
  if (user.exp < Date.now()) {
    // 直接进入页面
    // 路由跳转
    await router.push("/Home");
    return;
  }
  let refreshUser = JSON.parse(decodeURIComponent(escape(window.atob(refreshToken.split('.')[1]))))
  if (refreshUser.exp < Date.now()) {
    // 发起请求获取新的token
    console.log("getNew")
    let result = await getNewToken();
    if(!result) {
      return;
    }
    localStorage["token"] = result.token;
    localStorage["refreshToken"] = result.refreshToken;
    await useCheckToken();
    return;
  }
  clearStorage();
}

/**
 * 获取登录用户信息
 * @returns {any}
 */
export const useGetUserInfo = () => {
  return JSON.parse(atob(localStorage["user"]));
}

/**
 * 保存用户数据
 * @param result
 */
const useSaveUserInfo = (result) => {
  console.log(result)
  let user = {
    id: result.id,
    create_time: result.create_time,
    invitation_code: result.invitation_code,
    username: result.username
  };
  localStorage["id"] = result.id;
  localStorage["token"] = result.token;
  localStorage["refreshToken"] = result.refreshToken;
  localStorage["user"] = btoa(JSON.stringify(user));
}


